package com.myh.controller;

import com.myh.pojo.File;
import com.myh.pojo.User;
import com.myh.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static jdk.nashorn.internal.runtime.regexp.joni.Syntax.Java;

/**
 * @author 莫耀华
 * @date 2020-08-23 16:43
 */
@Controller
@RequestMapping("file")
@Transactional
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 根据id获取文件
     *
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/showAll")
    public String findALl(Model model, HttpSession session) {
        //从seesion获取用户id
        User user = (User) session.getAttribute("user");
        //通过用户id查询所有用户的文件
        List<File> listByUid = fileService.findListByUid(user.getId());
        //将数据添加到model中
        model.addAttribute("files", listByUid);
        return "showAll";
    }

    /**
     * 文件上传
     *
     * @param file
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request, HttpSession session) {
        try {
            //获取文件的原始名称
            String oldfileName = file.getOriginalFilename();
            if ("".equals(oldfileName)) {
                return "redirect:/file/showAll";
            }
            System.out.println("原文件名:" + oldfileName);
            //获取文件后缀
            String extensiog = "." + FilenameUtils.getExtension(file.getOriginalFilename());
            System.out.println("文件后缀:" + extensiog);
            //获取新的名称
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().substring(0, 10).replace("-", "") + extensiog;
            System.out.println("新文件名:" + newFileName);
            //文件的大小
            int szie = (int) file.getSize();
            System.out.println("文件的大小:" + szie);
            //文件类型
            String type = file.getContentType();
            System.out.println("文件类型:" + type);
            //处理文件上传的目录
            //根工具类  也可以使用 request.getServletContext().getRealPath("/upload");

//            String realPath=ResourceUtils.getURL("classpath:").getPath() + "/static/upload";
//            String realPath =  request.getSession().getServletContext().getRealPath("");
            String realPath = System.getProperty("user.dir") + "/upload/";
            System.out.println("realPath" + realPath);
            String dataDirPath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            System.out.println("文件目录:" + realPath + "/" + dataDirPath);
            //根据日期生成目录
            java.io.File dataDir = new java.io.File(realPath + "/" + dataDirPath);
            if (!dataDir.exists()) {
                //目录不存 就创建
                dataDir.mkdirs();
            }
            //处理文件上传
            file.transferTo(new java.io.File(realPath + "/" + dataDirPath, newFileName));
            //插入到数库中
            File fileDb = new File();
            User user = (User) session.getAttribute("user");
            fileDb.setUserId(user.getId());
            fileDb.setOldFileName(oldfileName);
            fileDb.setNewFileName(newFileName);
            fileDb.setExt(extensiog);
            fileDb.setPath("/upload/" + dataDirPath);
            fileDb.setSize(szie);
            fileDb.setType(type);
            //保存到数据库
            fileService.save(fileDb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/file/showAll";
    }

    /**
     * 文件下载
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取文件信息
        File byFid = fileService.findByFid(id);
        //查询文件不存在
        if (byFid == null) {
            return;
        }
        //设置不打开文件 以附件下载
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(byFid.getOldFileName(), "utf-8"));
        //根据文件信息中文名字1和文件储存路径获取文件输入流
        String realPath = System.getProperty("user.dir");
        //更新下载次数
        fileService.updateDownCountByFid(byFid.getId());
        //获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(realPath + byFid.getPath(), byFid.getNewFileName()));
        //获取响应流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    /**
     * 文件预览
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/lookFile/{id}")
    public void lookFile(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取文件信息
        File byFid = fileService.findByFid(id);
        //查询文件不存在
        if (byFid == null) {
            return;
        }
        //设置不打开文件 以附件下载
        response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode(byFid.getOldFileName(), "utf-8"));
        //根据文件信息中文名字1和文件储存路径获取文件输入流
        String realPath = System.getProperty("user.dir");
        //获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(realPath + byFid.getPath(), byFid.getNewFileName()));
        //获取响应流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    /**
     * 根据文件id删除文件
     *
     * @param id
     * @return
     * @throws FileNotFoundException
     */
    @GetMapping("/delete/{id}")
    public String deleteByFid(@PathVariable Integer id, HttpServletRequest request) throws FileNotFoundException {
        //获取文件信息
        File byFid = fileService.findByFid(id);
        //查询文件不存在
        if (byFid == null) {
            return "redirect:/file/showAll";
        }
        String realPath = System.getProperty("user.dir");
        java.io.File file = new java.io.File(realPath+byFid.getPath(), byFid.getNewFileName());
        //删除文件
        if (file.exists()) {
            file.delete();
        }
        //删除数据库
        fileService.deleteByFid(id);
        return "redirect:/file/showAll";
    }
}
